package org.gradle.image;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "BannerServlet", value = "/BannerServlet")
public class BannerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        问题产生的原因已经明了，getParameter方法会影响getInputStream方法获取流信息。
        System.out.println(request.getParameter("content"));
        BufferedInputStream in = new BufferedInputStream(request.getInputStream());
        byte[] b = new byte[1024];
        StringBuilder sb_utf = new StringBuilder(64);
        int i=0;
        do {
            i = in.read(b);
            if (i > 0) {
                sb_utf.append(new String(b, 0, i,"UTF-8"));
            }
        } while(i == 1024);
        System.out.println(sb_utf.toString());
        System.out.println(request.getParameter("content"));
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setContentType("application/json; charset=utf-8");

        PrintWriter pw = response.getWriter();
        List<BannerBean> bannerBeanList = new ArrayList<>();
        BannerBean bean = new BannerBean();
        bean.setImg("http://192.0.0.153:8080/static/img/a.jpg");
        bean.setUrl("http://www.baidu.com/");
        bannerBeanList.add(bean);

        bean = new BannerBean();
        bean.setImg("http://192.0.0.153:8080/static/img/b.jpg");
        bean.setUrl("http://www.baidu.com/");
        bannerBeanList.add(bean);

        bean = new BannerBean();
        bean.setImg("http://192.0.0.153:8080/static/img/c.jpg");
        bean.setUrl("http://www.baidu.com/");
        bannerBeanList.add(bean);

        pw.write(JSON.toJSONString(bannerBeanList));
        pw.flush();
        pw.close();
    }
}
